package com.huhao.wshare.Profile;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.R;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import static com.huhao.wshare.Config.GET_USER_PROFILE_API;
import static com.huhao.wshare.Config.PROFILE_UPLOAD_API;
import static com.huhao.wshare.Config.UPDATE_USER_PROFILE_API;
import static com.huhao.wshare.Config.FILE_UPLOAD_API; // 假设从Config获取上传接口

public class UpdateProfileActivity extends BaseActivity {
    private TextInputEditText etUsername, etSigns, etEmail, etPhone;
    private RadioGroup rgGender;
    private RadioButton rbMale, rbFemale;
    private ImageView ivAvatar, ivBackgroundPreview;
    private Button btnSave;
    private String userId, token, currentUploadType; // currentUploadType: "avatar"或"bkImg"
    private OkHttpClient client;

    // 权限和图片选择相关组件（参考ReleaseDynamicActivity）
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private ActivityResultLauncher<Intent> imagePickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_profile);

        // 初始化OkHttpClient（设置超时，参考ReleaseDynamicActivity）
        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        initViews();
        initImageUploadListeners();
        initActivityLaunchers(); // 初始化权限和图片选择Launcher

        // 从SharedPreferences获取用户ID和token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        userId = String.valueOf(sp.getInt("id", -1));
        token = sp.getString("token", null);

        if (userId != null && !userId.equals("-1") && token != null) {
            fetchUserProfile(); // 加载用户信息
        } else {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etSigns = findViewById(R.id.et_signs);
        etEmail = findViewById(R.id.et_email);
        etPhone = findViewById(R.id.et_phone);
        rgGender = findViewById(R.id.rg_gender);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        ivAvatar = findViewById(R.id.iv_avatar);
        ivBackgroundPreview = findViewById(R.id.iv_background_preview);
        btnSave = findViewById(R.id.btn_save);

        // 保存按钮点击事件（原有功能）
        btnSave.setOnClickListener(v -> updateProfile());
    }

    // 初始化图片上传点击事件（头像和背景图）
    private void initImageUploadListeners() {
        // 头像点击事件
        ivAvatar.setOnClickListener(v -> {
            currentUploadType = "avatar"; // 标记为头像上传
            checkPermissionAndOpenPicker();
        });

        // 背景图上传按钮点击事件
        FloatingActionButton btnUploadBackground = findViewById(R.id.btn_upload_background);
        btnUploadBackground.setOnClickListener(v -> {
            currentUploadType = "bkImg"; // 标记为背景图上传
            checkPermissionAndOpenPicker();
        });
    }

    // 初始化权限请求和图片选择的Launcher（参考ReleaseDynamicActivity）
    private void initActivityLaunchers() {
        // 权限请求Launcher
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        openImagePicker();
                    } else {
                        Toast.makeText(this, "需要存储权限访问相册", Toast.LENGTH_SHORT).show();
                    }
                });

        // 图片选择回调Launcher
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        handleImageSelection(result.getData());
                    }
                });
    }

    // 检查权限并打开图片选择器（参考ReleaseDynamicActivity的权限逻辑）
    private void checkPermissionAndOpenPicker() {
        String requiredPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
            requiredPermission = Manifest.permission.READ_MEDIA_IMAGES;
        } else { // Android 12及以下
            requiredPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (ContextCompat.checkSelfPermission(this, requiredPermission)
                == PackageManager.PERMISSION_GRANTED) {
            openImagePicker(); // 权限已授予，直接打开相册
        } else {
            requestPermissionLauncher.launch(requiredPermission); // 请求权限
        }
    }

    // 打开系统相册选择图片
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        imagePickerLauncher.launch(intent);
    }

    // 处理选择的图片
    private void handleImageSelection(Intent data) {
        Uri imageUri = data.getData();
        if (imageUri != null) {
            try {
                // 将Uri转换为File（参考ReleaseDynamicActivity的getFileBytesFromUri）
                File imageFile = uriToFile(imageUri);
                if (imageFile != null) {
                    uploadImage(imageFile); // 上传图片
                }
            } catch (Exception e) {
                Log.e("UpdateProfile", "图片处理失败", e);
                Toast.makeText(this, "图片处理失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 将Uri转换为File（参考ReleaseDynamicActivity的getFileBytesFromUri）
    private File uriToFile(Uri uri) throws IOException {
        try (InputStream inputStream = getContentResolver().openInputStream(uri);
             ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }

            // 创建临时文件
            File tempFile = new File(getExternalCacheDir(), getFileNameFromUri(uri));
            tempFile.createNewFile();
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(byteBuffer.toByteArray());
            }
            return tempFile;
        }
    }

    // 从Uri获取文件名（复用ReleaseDynamicActivity逻辑）
    private String getFileNameFromUri(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (columnIndex != -1) {
                        result = cursor.getString(columnIndex);
                    }
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    // 上传图片到服务器
    private void uploadImage(File imageFile) {
        if (token == null || currentUploadType == null) return;

        // 构建Multipart请求体（符合接口要求）
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imageFile.getName(),
                        RequestBody.create(MediaType.parse("image/*"), imageFile))
                .addFormDataPart("type", currentUploadType) // 指定上传类型
                .build();

        // 构建请求
        Request request = new Request.Builder()
                .url(PROFILE_UPLOAD_API)
                .addHeader("Authorization", "Bearer " + token)
                .post(requestBody)
                .build();

        // 发送异步请求
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    Log.e("UploadError", "图片上传失败", e);
                    Toast.makeText(UpdateProfileActivity.this, "上传失败，请重试", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
                try (ResponseBody body = response.body()) {
                    if (response.isSuccessful() && body != null) {
                        String responseStr = body.string();
                        Log.d("UploadResponse", responseStr);

                        // 解析响应
                        try {
                            JSONObject json = new JSONObject(responseStr);
                            if (json.optInt("code") == 200) {
                                runOnUiThread(() -> {
                                    Toast.makeText(UpdateProfileActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                    fetchUserProfile(); // 重新加载用户信息，更新UI
                                });
                            } else {
                                runOnUiThread(() ->
                                        Toast.makeText(UpdateProfileActivity.this,
                                                "上传失败: " + json.optString("message"),
                                                Toast.LENGTH_SHORT).show()
                                );
                            }
                        } catch (Exception e) {
                            runOnUiThread(() -> {
                                Log.e("UploadParseError", "解析响应失败", e);
                                Toast.makeText(UpdateProfileActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show();
                            });
                        }
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(UpdateProfileActivity.this, "服务器错误", Toast.LENGTH_SHORT).show()
                        );
                    }
                }
            }
        });
    }

    // 以下为原有功能代码（未修改）
    private void fetchUserProfile() {
        Request request = new Request.Builder()
                .url(GET_USER_PROFILE_API + "/" + userId)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(UpdateProfileActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    finish();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String respStr = response.body() != null ? response.body().string() : "";
                    runOnUiThread(() -> handleProfileResponse(respStr));
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(UpdateProfileActivity.this, "获取用户信息失败，请稍后重试", Toast.LENGTH_SHORT).show();
                        finish();
                    });
                }
            }
        });
    }

    private void handleProfileResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    // 设置用户名
                    etUsername.setText(data.optString("username"));
                    // 设置个性签名
                    etSigns.setText(data.optString("signs"));
                    // 设置邮箱
                    etEmail.setText(data.optString("email"));
                    // 设置手机号
                    etPhone.setText(data.optString("phone"));
                    // 设置性别
                    String gender = data.optString("gender");
                    if ("man".equals(gender)) rbMale.setChecked(true);
                    else if ("woman".equals(gender)) rbFemale.setChecked(true);

                    // 加载头像
                    String avatarUrl = data.optString("avatar");
                    if (!data.isNull("avatar") && !avatarUrl.isEmpty()) {
                        Glide.with(this).load(avatarUrl).into(ivAvatar);
                    } else {
                        ivAvatar.setImageResource("man".equals(gender) ?
                                R.drawable.default_avatar_man : R.drawable.default_avatar_woman);
                    }

                    // 加载背景图
                    String bkImgUrl = data.optString("bkImg");
                    if (!data.isNull("bkImg") && !bkImgUrl.isEmpty()) {
                        Glide.with(this).load(bkImgUrl).into(ivBackgroundPreview);
                    } else {
                        ivBackgroundPreview.setImageResource(R.drawable.default_background);
                    }
                }
            } else {
                Toast.makeText(this, json.optString("message"), Toast.LENGTH_SHORT).show();
                finish();
            }
        } catch (Exception e) {
            Toast.makeText(this, "解析用户信息失败", Toast.LENGTH_SHORT).show();
            Log.e("UpdateProfile", "解析 JSON 失败", e);
            finish();
        }
    }

    private void updateProfile() {
        try {
            JSONObject jsonBody = new JSONObject();
            String username = etUsername.getText().toString().trim();
            String signs = etSigns.getText().toString().trim();
            String email = etEmail.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String gender = rgGender.getCheckedRadioButtonId() == R.id.rb_male ? "man" :
                    (rgGender.getCheckedRadioButtonId() == R.id.rb_female ? "woman" : null);

            if (!username.isEmpty()) jsonBody.put("username", username);
            if (!signs.isEmpty()) jsonBody.put("signs", signs);
            if (!email.isEmpty()) jsonBody.put("email", email);
            if (!phone.isEmpty()) jsonBody.put("phone", phone);
            if (gender != null) jsonBody.put("gender", gender);

            if (jsonBody.length() == 0) {
                Toast.makeText(this, "没有需要更新的信息", Toast.LENGTH_SHORT).show();
                return;
            }

            RequestBody body = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    jsonBody.toString()
            );

            Request request = new Request.Builder()
                    .url(UPDATE_USER_PROFILE_API)
                    .put(body)
                    .addHeader("Authorization", "Bearer " + token)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() ->
                            Toast.makeText(UpdateProfileActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String respStr = response.body() != null ? response.body().string() : "";
                        runOnUiThread(() -> handleUpdateResponse(respStr));
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(UpdateProfileActivity.this, "更新失败，手机号或邮箱已被使用", Toast.LENGTH_SHORT).show()
                        );
                    }
                }
            });
        } catch (Exception e) {
            Log.e("UpdateProfile", "构建请求失败", e);
            Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleUpdateResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            if (json.optInt("code") == 200) {
                Toast.makeText(this, "用户信息更新成功！", Toast.LENGTH_SHORT).show();
                fetchUserProfile();
            } else {
                Toast.makeText(this, json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("UpdateProfile", "解析更新响应失败", e);
            Toast.makeText(this, "解析响应失败", Toast.LENGTH_SHORT).show();
        }
    }
}